<?php
/**
 * Created by PhpStorm.
 * User: fuyu
 * Date: 2018/6/20
 * Time: 下午4:33
 */

namespace App\Http\Controllers;


use App\Models\OrderSource;
use Illuminate\Http\Request;

class OrderSourceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function add(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|unique:order_source,name'
        ]);
        OrderSource::create($request->post());
        return jsonSuccess('添加成功');
    }

    public function modify(Request $request)
    {
        $this->validate($request,[
            'id' => 'required',
            'name' => 'required|unique:order_source,name'
        ]);
        $orderSource = OrderSource::find($request->post('id'));
        if (empty($orderSource)) {
            return jsonFail('找不到该订单源信息');
        }
        $orderSource->name = $request->post('name');
        $orderSource->save();
        return jsonSuccess('修改成功');
    }

    public function list(Request $request)
    {
        $pageSize = $request->input('page_size',20);
        $keyword = $request->input('keyword','');
        if($keyword==''){
            $sources = OrderSource::select()->orderBy('id', 'desc')->paginate($pageSize);
        }else{
            $sources = OrderSource::where('name', 'like', '%'.$keyword.'%')
            ->orderBy('id', 'desc')->paginate($pageSize);
        }
        
        $pagination = ['current_page'=>$sources->currentPage(),'last_page'=>$sources->lastPage(),'total'=>$sources->total()];
        return jsonSuccess('获取成功',['list'=>$sources->items(),'pagination'=>$pagination]);
    }

    public function info (Request $request)
    {
        $this->validate($request,[
            'id' => 'required',
        ]);
        $id = $request->get('id');
        $orderSource = OrderSource::find($id);
        if (empty($orderSource)) {
            return jsonFail('找不到该记录');
        }
        return jsonSuccess('获取成功',$orderSource);
    }

    public function delete(Request $request)
    {
        $this->validate($request,[
            'id' => 'required',
        ]);
        $id = $request->get('id');
        $orderSource = OrderSource::find($id);
        if (empty($orderSource)) {
            return jsonFail('找不到该记录');
        }
        $orderSource->delete();
        return jsonSuccess('删除成功');
    }

}